import { imgUploadUrl } from 'js/config'
import app from '../../main'

class RichEditor {
  // new 构造
  constructor(bar, content, token, goodsId, storeId, callback) {
    this.editorBar = document.getElementById(bar)
    this.editorCon = document.getElementById(content)
    this.token = token
    this.goodsId = goodsId
    this.storeId = storeId
    this.iframeDoc = null
    this.callback = callback
    this.init()
  }

  // 初始化
  init() {
    this.createIframe()
    this.bindEditorBtn()
  }

  // 创建iframe
  createIframe() {
    const iframe = document.createElement('iframe')
    // 框架大小与编辑区大小一样
    iframe.width = `${$(this.editorCon).width()}px`
    iframe.height = `${$(this.editorCon).height()}px`
    iframe.frameBorder = 0
    iframe.scrolling = 'auto'
    iframe.name = 'editor'
    // 在this.editorCon子节点前插入iframe子节点，因此需要取得this.editorCon.parentNode父节点
    this.editorCon.parentNode.insertBefore(iframe, this.editorCon)
    iframe.style.display = 'block'
    // textarea不显示
    this.editorCon.style.display = 'none'
    // 操作iframe内contentDocument中的元素
    this.iframeDoc = iframe.contentDocument || iframe.contentWindow.document
    // 在iframe中编辑，则设置为on，如果是要想在div中编辑，设置其contentEditable = 'true'
    this.iframeDoc.designMode = 'on'
    this.iframeDoc.canHaveHTML = true
    this.iframeDoc.getElementsByTagName('body')[0].innerHTML = this.editorCon.value
    this.iframeDoc.onkeyup = () => {
      this.getIframeValue()
    }
  }

  // 绑定操作条控制
  bindEditorBtn() {
    const aToolBtn = this.getEditorBarBtns()
    Array.from(aToolBtn).forEach(item => {
      item.addEventListener('click', (ev) => {
        ev.preventDefault()
        ev.stopPropagation()
        const ec = item.getAttribute('ec')
        if (ec === 'FontSize') {
          this.execCommand(ec, false, item.getAttribute('size'))
        } else if (ec === 'insertImage') {
          const flag = item.getAttribute('flag')
          if (flag === 'local') {
            this.createUploadForm((src) => {
              this.execCommand(ec, false, src)
            })
          } else {
            const src = prompt('图片地址', '')
            src ? this.execCommand(ec, false, src) : null
          }
        } else {
          this.execCommand(ec, false, null)
          this.getIframeValue()
        }
        this.iframeDoc.body.focus()
      }, false)
    })
  }

  /*
    execCommand:方法是执行一个对当前文档，当前选择或者给出范围的命令
    command：要执行的命令的名称
    showUI：boolean是否向用户显示命令特定的对话框或消息框
    value类型：string要使用该命令分配的值
  */
  execCommand(command, show, value) {
    if (command === 'blockquote') {
      this.iframeDoc.execCommand('formatBlock', true, '<blockquote>')
      const aBlockquote = this.iframeDoc.getElementsByTagName('blockquote')
      Array.from(aBlockquote).forEach(ele => {
        ele.style.margin = '0'
        ele.style.padding = '12px'
        ele.style.background = '#eee'
        ele.style.borderLeft = '4px solid #ddd'
      })
    } else if (command === 'createLink') {
      const href = prompt('链接地址', 'http://')
      href ? this.iframeDoc.execCommand(command, show, href) : null
    } else {
      this.iframeDoc.execCommand(command, show, value)
    }
  }

  // 创建form表单
  createUploadForm(callback) {
    // 创建form表单
    const oForm = $(`<form action="${imgUploadUrl}" method="post" enctype="multipart/form-data" style="opacity: 0;"></form>`)
    const oInput = $(`<input type="file" name="imgFile" />` +
                  `<input type="hidden" value=${this.token} name="accessToken" />` +
                  `<input type="hidden" value=goodsDetail name="uploadType" />` +
                  `<input type="hidden" value="" name="oldFileName" />` +
                  `<input type="hidden" value=${this.goodsId} name="goodsId" />` +
                  `<input type="hidden" value=${this.storeId} name="storeId" />`)
    const oFormInput = oForm.append(oInput)
    $('body').append(oFormInput)
    oInput.click()
    this.uploadLocalImg(oInput, oForm, callback)
  }

  // 图片上传
  uploadLocalImg(oInput, oForm, callback) {
    const _this = this
    oInput.on('change', function (ev) {
      if (!/.jpg|.jepg|.png/i.test(ev.target.value)) {
        app.$toast('图片格式无效，请重新选择')
        return
      }
      oForm.ajaxSubmit(data => {
        callback && callback(data.data.photoUrl || '')
        _this.getIframeValue()
        oForm.remove()
      })
    })
  }

  // 获取输入的值
  getIframeValue() {
    this.callback && this.callback(this.iframeDoc.getElementsByTagName('body')[0].innerHTML)
  }

  // 获取所有操作按钮
  getEditorBarBtns() {
    return this.editorBar.getElementsByTagName('button')
  }
}

export default RichEditor